package com.junsi.web.controller.demo;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.codec.binary.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.junsi.common.annotation.Log;
import com.junsi.common.core.controller.BaseController;
import com.junsi.common.core.domain.AjaxResult;
import com.junsi.common.core.page.TableDataInfo;
import com.junsi.common.enums.BusinessType;
import com.junsi.common.utils.oss.OssClient;
import com.junsi.common.utils.poi.ExcelUtil;
import com.junsi.demo.domain.Demo;
import com.junsi.demo.service.IDemoService;
import com.junsi.framework.util.ShiroUtils;
import com.junsi.system.domain.SysFile;
import com.junsi.system.service.ISysFileService;

/**
 * 测试用例 信息操作处理
 * 
 * @author junsi
 * @date 2019-08-17
 */
@Controller
@RequestMapping("/sys/demo")
public class DemoController extends BaseController
{
	@Value("${aliyun.oss.replace-url}")
	private String replaceUrl;
	
	@Value("${server.servlet.context-path}")
	private String contextPath;
	
    private String prefix = "demo";
	
	@Autowired
	private IDemoService demoService;
	
	@Autowired
	private ISysFileService sysFileService;
	
	@RequiresPermissions("sys:demo:view")
	@GetMapping()
	public String demo()
	{
	    return prefix + "/demo";
	}
	
	/**
	 * 查询测试用例列表
	 */
	@RequiresPermissions("sys:demo:list")
	@PostMapping("/list")
	@ResponseBody
	public TableDataInfo list(Demo demo)
	{
		startPage();
        List<Demo> list = demoService.selectDemoList(demo);
		return getDataTable(list);
	}
	
	
	/**
	 * 导出测试用例列表
	 */
    @Log(title = "测试用例", businessType = BusinessType.EXPORT)
	@RequiresPermissions("sys:demo:export")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(Demo demo)
    {
    	List<Demo> list = demoService.selectDemoList(demo);
        ExcelUtil<Demo> util = new ExcelUtil<Demo>(Demo.class);
        return util.exportExcel(list, "demo");
    }
	
	/**
	 * 新增测试用例
	 */
	@GetMapping("/add")
	public String add()
	{
	    return prefix + "/add";
	}
	
	/**
	 * 新增保存测试用例
	 */
	@RequiresPermissions("sys:demo:add")
	@Log(title = "测试用例", businessType = BusinessType.INSERT)
	@PostMapping("/add")
	@ResponseBody
	public AjaxResult addSave(Demo demo)
	{		
		return toAjax(demoService.insertDemo(demo));
	}

	/**
	 * 修改测试用例
	 */
	@GetMapping("/edit/{id}")
	public String edit(@PathVariable("id") Integer id, ModelMap mmap)
	{
		Demo demo = demoService.selectDemoById(id);
		
		SysFile sysFile = new SysFile();
		sysFile.setBelongId(id+"");
		List<SysFile> fileList = sysFileService.selectSysFileList(sysFile);
		List<String> fileUrlList = new ArrayList<String>();
		List<String> ossFileUrlList = new ArrayList<String>();
		for (SysFile file : fileList) {
			if(StringUtils.equals(file.getBelongType(), "demo-oss")) {
				ossFileUrlList.add(OssClient.getTmpUrl(file.getFileUrl().replace(replaceUrl,"")));
			} else if(StringUtils.equals(file.getBelongType(), "demo")) {
				fileUrlList.add(contextPath + "/profile/" + file.getFileUrl());
			}
		}
		
		mmap.put("demo", demo);
		mmap.put("fileUrlList", fileUrlList);
		mmap.put("ossFileUrlList", ossFileUrlList);
	    return prefix + "/edit";
	}
	
	/**
	 * 修改保存测试用例
	 */
	@RequiresPermissions("sys:demo:edit")
	@Log(title = "测试用例", businessType = BusinessType.UPDATE)
	@PostMapping("/edit")
	@ResponseBody
	public AjaxResult editSave(Demo demo)
	{		
		return toAjax(demoService.updateDemo(demo));
	}
	
	/**
	 * 删除测试用例
	 */
	@RequiresPermissions("sys:demo:remove")
	@Log(title = "测试用例", businessType = BusinessType.DELETE)
	@PostMapping( "/remove")
	@ResponseBody
	public AjaxResult remove(String ids)
	{		
		return toAjax(demoService.deleteDemoByIds(ids));
	}

    /**
     * oss附件上传
     */
    @Log(title = "oss附件上传", businessType = BusinessType.UPDATE)
    @PostMapping("/ossUpload")
    @ResponseBody
    public AjaxResult ossUpload(@RequestParam("id") String id, @RequestParam("ossFile") MultipartFile file)
    {
		String user = ShiroUtils.getLoginName();
		
		try {
			SysFile sysFile = sysFileService.ossUploadFile(file, id, "demo-oss", 1, user);
			if(sysFile!=null) {
				String filePath = OssClient.getTmpUrl(sysFile.getFileUrl().replace(replaceUrl,""));
				System.out.println("文件的访问路径：" + filePath);
				return AjaxResult.success("上传成功", filePath);
			}
		} catch (IOException e) {
			logger.error("oss附件上传出错", e);
		}
		return error("ossUpload error");
    }
    
    /**
     * 附件上传
     */
    @Log(title = "附件上传", businessType = BusinessType.UPDATE)
    @PostMapping("/upload")
    @ResponseBody
    public AjaxResult upload(@RequestParam("id") String id, @RequestParam("file") MultipartFile file)
    {
		String user = ShiroUtils.getLoginName();

		try {
			SysFile sysFile = sysFileService.uploadFile(file, id, "demo", 1, user);
			if(sysFile!=null) {
				String filePath = sysFile.getFileUrl();
				System.out.println("文件的访问路径：" + filePath);
				return AjaxResult.success("上传成功", contextPath + "/profile/" + filePath);
			}
		} catch (IOException e) {
			logger.error("附件上传出错", e);
		}
		return AjaxResult.error("upload error");
    }

	/**
	 * 多数据源测试
	 * <br/>
	 * DataSource(value = DataSourceType.SLAVE) 注解可以加到 service 中，也可以加到 mapper 中
	 *   1、注解可以加到类上面
	 *   2、注解可以加到方法上面
	 */
	@GetMapping("/dataSource")
	@ResponseBody
	public String dataSource()
	{
		// 默认数据源
		Demo demo = demoService.selectDemoById(1);

		// 查询测试用例信息 slave 第二数据库（注解加到 service 实现类中）
		Demo demo1 = demoService.selectDemoById_slave4Service(1);

		// 查询测试用例信息 slave 第二数据库（注解加到 mapper 接口中）
		Demo demo2 = demoService.selectDemoById_slave4Mapper(1);

		return "默认数据源master：" + demo.toString() + "<br/>第二数据源slave，service注入：" + demo1.toString() + "<br/>第二数据源slave，mapper注入：" + demo2.toString();
	}

}
